package com.jc.base;

import com.jc.utils.StringUtils;

/**
 * 业务异常
 *
 * @author lrh
 */
public class ComponentException extends RuntimeException {

	private static final long serialVersionUID = 6757986084644052746L;

	private ErrCode errCode;

	private String message;

	/**
	 * 异常码
	 */
	public interface ErrCode {

		ErrCode 系统异常 = new ErrCode() {
			@Override
			public String code() {
				return "ECP-0000";
			}

			@Override
			public String name() {
				return "系统异常";
			}
		};
		ErrCode 参数非法 = new ErrCode() {

			@Override
			public String code() {
				return "ECP-0001";
			}

			@Override
			public String name() {
				return "参数非法";
			}
		};
		ErrCode 数据错误 = new ErrCode() {

			@Override
			public String code() {
				return "ECP-0002";
			}

			@Override
			public String name() {
				return "数据错误";
			}
		};

		ErrCode 操作非法 = new ErrCode() {

			@Override
			public String code() {
				return "ECP-0003";
			}

			@Override
			public String name() {
				return "操作非法";
			}
		};

		ErrCode 性能不良 = new ErrCode() {

			@Override
			public String code() {
				return "ECP-0004"; // 监控
			}

			@Override
			public String name() {
				return "性能不良";
			}
		};

		ErrCode 加锁失败 = new ErrCode() {

			@Override
			public String code() {
				return "ECP-0005"; // 监控
			}

			@Override
			public String name() {
				return "加锁失败";
			}
		};

		ErrCode 访问过多 = new ErrCode() {

			@Override
			public String code() {
				return "-3";
			}

			@Override
			public String name() {
				return "访问过于频繁";
			}
		};

		ErrCode 系统繁忙 = new ErrCode() {

			@Override
			public String code() {
				return "-4";
			}

			@Override
			public String name() {
				return "系统繁忙，请稍后重试!";
			}
		};

		/**
		 * 异常码
		 *
		 * @return
		 */
		String code();

		/**
		 * 异常码说明
		 *
		 * @return
		 */
		String name();
	}

	public ComponentException(ErrCode errCode) {
		this(errCode, "");
	}

	public ComponentException(ErrCode errCode, String message) {
		this(errCode, message, null);
	}

	public ComponentException(ErrCode errCode, Throwable cause) {
		this(errCode, "", cause);
	}

	public ComponentException(ErrCode errCode, String message, Throwable cause) {
		super("ERROR CODE: " + errCode.code() + "[" + errCode.name() + "]"
				+ message, cause); // NOI18N
		this.message = message;
		this.errCode = errCode;
	}

	public final String getErrCode() {
		return errCode.code();
	}

	public final String getErrCodeMsg() {
		String custMsg = ErrMsgManager.getErrMsg(errCode.code());
		if (StringUtils.isNotEmpty(custMsg)) {
			return custMsg;
		}
		return StringUtils.isNotEmpty(this.message) ? this.message : errCode
				.name();
	}

	public final ErrCode getCode() {
		return errCode;
	}

}
